import React, { memo, useState } from 'react';
import { Dropdown, Menu } from 'antd';
import styles from './index.less';
import Dots from '../Dots';
import ExpressEditor from '../ExpressEditor';
import { connect } from 'umi';
import { findNodeById } from '@/utils';

function StringProp(props: API.IStringProp) {
  const { project, saveNodeChange } = props as any;

  const currentNode = findNodeById(project.pageConfig, project.currentCompId);
  let value;
  try {
    value = JSON.parse(props.value || '{}').value;
  } catch (error) {
    value = currentNode?.children + '';
  }

  const [bindType, setBindType] = useState('string');
  const handleSelect = (e: any) => {
    setBindType(e.key);
  };
  const handleCodeChange = (e: any) => {
    if (!currentNode) return;
    const value = bindType === 'string' ? e?.target?.value : e.doc.getValue();
    props.onChange &&
      props.onChange(JSON.stringify({ type: bindType, value: value }));
    // 更新节点信息
    if (!props.propName) return;
    if (props.propName === 'children')
      currentNode.children = value;
    else currentNode!.props[props.propName] = value;
    saveNodeChange(currentNode);
  };
  const menu = (
    <Menu
      onClick={handleSelect}
      items={[
        { label: '字符串', key: 'string' },
        { label: '表达式', key: 'express' },
        { label: '方法', key: 'function' },
      ]}
    />
  );

  return (
    <div>
      <label htmlFor="">{props.name}</label>
      <div className={styles.stirngProp}>
        <ExpressEditor
          type={bindType}
          onChange={handleCodeChange}
          value={value}
        />
        <Dropdown overlay={menu}>
          <a href="javascript:">
            <Dots />
          </a>
        </Dropdown>
      </div>
    </div>
  );
}

export default connect(({ project }: any) => ({ project }), {
  saveNodeChange: (payload: any) => ({
    type: 'project/saveNodeChange',
    payload,
  }),
})(memo(StringProp));
